package com.bsc.relay.service;

import java.io.IOException;
import java.net.InetSocketAddress;


import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientServer {

    private int port;
    private String host;
    private SocketConnector connector;
    private IoSession session;
    private long CONNECT_TIMEOUT = 30 * 1000L;
    private static final Logger LOGGER = LoggerFactory.getLogger(ClientServer.class);

    public ClientServer(String host, int port, long timeout) {
        this.host = host;
        this.port = port;
        this.CONNECT_TIMEOUT = timeout;
        connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(CONNECT_TIMEOUT);
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("protocol",
                new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        connector.setHandler(new ClientHandler());
        connector.setDefaultRemoteAddress(new InetSocketAddress(host, port));
    }

//    private static IoHandler createIoHandler() {
//        /*
//         * 使用ServerHandler创建状态机。
//         * 通知状态机工厂使用@IoHandlerTransition标签创建状态机。
//         * 使用IoHandlerTransition标签创建ServerHandler实例，
//         * 该实例中所有方法进加入IoHandlerTaransition标签，
//         * 当输入流(command)中含有对应方名的指令，则方法被调用
//         */
//        StateMachine sm = StateMachineFactory.getInstance(
//                IoHandlerTransition.class).create(ClientHandler.CONNECTED,
//                new ClientHandler());
//        /**
//         * 创建IoHandler实例
//         * 设置IoSession状态查找
//         * 状态内容工厂创建TetrisServerContext状态实例，并将该实例加入到IoSession状态中。
//         **/
//        return new StateMachineProxyBuilder().setStateContextLookup(
//                new IoSessionStateContextLookup(new StateContextFactory() {
//
//            public StateContext create() {
//                return new ClientHandler.TetrisServerContext();
//            }
//        })).create(IoHandler.class, sm);
//    }
    public IoSession getSession() {
        return session;
    }

    public void start() throws IOException {
        ConnectFuture connectFuture = connector.connect();
        connectFuture.awaitUninterruptibly(CONNECT_TIMEOUT);
        try {
            session = connectFuture.getSession();
        } catch (RuntimeIoException e) {
            LOGGER.warn(e.getMessage(), e);
        }
    }
}
